package service.impl.security;

import java.util.List;

import service.impl.BaseDataServiceImpl;
import service.interf.security.IUser;

import common.impl.MD5Transform;
import common.impl.exception.ServiceException;

import dao.interf.IUserDAO;
import dao.pojo.User;

/**
 * Title:UserImpl Description:用户相关
 * 
 * @author yanglei
 * @since 2012-02-28
 * @version 1.0
 */
public class UserImpl extends BaseDataServiceImpl implements IUser {

	/** 安全用户接口 */
	private IUserDAO iUserDao;

	/** 安全用户信息接口 */

	/**
	 * Title:setiUserDao Description:为Spring框架注入IUserDAO提供方法
	 * 
	 * @param iUserDao
	 *            传入安全用户服务
	 */
	public void setiUserDao(IUserDAO iUserDao) {
		this.iUserDao = iUserDao;
	}

	/**
	 * Title：updUserPwd Description： 修改用户密码
	 * 
	 * @param userId
	 *            用户编号
	 * @param oldPwd
	 *            旧密码
	 * @param newPwd
	 *            旧密码
	 * @return 1
	 * @throws Exception
	 */
	public String updUserPwd(Long userId, String oldPwd, String newPwd)
			throws Exception {
		List<User> lstUser = null;
		try {
			lstUser = iUserDao.findByProperties(new String[] { "userId",
					"password" }, new Object[] { userId,
					MD5Transform.EncoderByMd5(oldPwd, "utf-8") });
		} catch (Exception e) {
			throw new ServiceException("ERR-0003");
		}

		if (null == lstUser || lstUser.isEmpty())
			throw new ServiceException("ERR-0002");
		User user = lstUser.get(0);
		user.setPassword(MD5Transform.EncoderByMd5(newPwd, "utf-8"));
		iUserDao.update(user);
		return "1";
	}

	/**
	 * 重设管理密码
	 */
	public String resetPassword(User model) throws Exception {
		List<User> ul = null;
		try {
			ul = iUserDao.findByProperties(new String[] { "userName" },
					new Object[] { model.getUserName() });
		} catch (Exception e) {
			throw new ServiceException("ERR-0002");
		}
		User user = ul.get(0);
		user.setPassword(MD5Transform
				.EncoderByMd5(model.getPassword(), "utf-8"));
		iUserDao.update(user);
		return "1";
	}

	public Boolean useUnableByIds(String ids) throws ClassNotFoundException,
			RuntimeException {
		String[] idArr = ids.split(",");
		Short o = 0;
		for (int i = 0, len = idArr.length; i < len; i++) {
			User user = iUserDao.findById(Long.valueOf(idArr[i]));
			if (null == user) {
				return false;
			}
			user.setEnabled(o);// 将用户使能值设为0，禁用该用户
			iUserDao.update(user);
		}
		return true;
	}

	public Boolean useableByIds(String ids) throws ClassNotFoundException,
			RuntimeException {
		String[] idArr = ids.split(",");
		Short o = 1;
		for (int i = 0, len = idArr.length; i < len; i++) {
			User user = iUserDao.findById(Long.valueOf(idArr[i]));
			if (null == user) {
				return false;
			}
			user.setEnabled(o);// 将用户使能值设为1，激活该用户
			iUserDao.update(user);
		}
		return true;
	}
}
